<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>带食物系统的贪吃蛇</title>
    <style>
        :root {
            --primary: #2C3E50;
            --secondary: #3498DB;
            --accent: #2ECC71;
            --light: #F5F5F5;
            --danger: #E74C3C;
            --warning: #F39C12;
            --dark: #34495E;
            --text: #333;
            --border-radius: 6px;
            --box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .game-container {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            gap: 20px;
            margin: 20px;
        }
        #game-board {
            width: 800px;
            height: 800px;
            border: 2px solid #2c3e50;
            background: #ecf0f1;
            position: relative;
        }
        .snake-cell {
            width: 40px;
            height: 40px;
            background: #27ae60;
            position: absolute;
            border-radius: 5px;
        }
        #food {
            width: 40px;
            height: 40px;
            background: #e74c3c;
            position: absolute;
            border-radius: 50%;
        }
        .score-board {
            text-align: center;
            font: 40px Arial;
            color: #34495e;
        }
        .controls {
            margin-top: 30vh;
            display: grid;
            grid-template-columns: repeat(3, 40px);
            grid-template-rows: repeat(3, 40px);
            gap: 5px;
            padding: 10px;
        }
        .controls button {
            font-size: 24px;
            padding: 5px;
            cursor: pointer;
            background: rgba(76, 201, 240, 0.1);
            border-radius: 5px;
            border: 2px solid #4cc9f0;
            color: #000;
        }
        #up-btn {
            grid-column: 2;
            grid-row: 1;
        }
        #left-btn {
            grid-column: 1;
            grid-row: 2;
        }
        #right-btn {
            grid-column: 3;
            grid-row: 2;
        }
        #down-btn {
            grid-column: 2;
            grid-row: 3;
        }
        #btn-start {
            grid-column: 1 / span 3;
            grid-row: 4;
            margin-top: 20px;
            font-size: 16px;
            padding: 8px 15px;
            background-color: #2ecc71;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        #btn-start:hover {
            background-color: #27ae60;
        }
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            background: var(--accent);
            color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            transform: translateY(-100px);
            opacity: 0;
            transition: all 0.5s;
        }
        
        .notification.show {
            transform: translateY(0);
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="score-board">得分：<span id="score">0</span></div>
    <div class="game-container">
        <div id="game-board"></div>
        <div class="controls">
            <button id="up-btn">↑</button>
            <button id="left-btn">←</button>
            <button id="right-btn">→</button>
            <button id="down-btn">↓</button>
            <button id="btn-start">游戏开始</button>
        </div>
    </div>

    <div id="notification" class="notification">
        <span id="notificationText">操作成功</span>
    </div>

    <script>
        // 核心参数配置
        const CELL_SIZE = 40;
        let snake = [{x: 400, y: 400}];
        let direction = 'right';
        let food = generateFood();
        let score = 0;
        let isGameRunning = false; // 初始状态为非运行
        let gameInterval;
        
        const notification = document.getElementById('notification');

        // 智能食物生成算法（网页6、网页10）
        function generateFood() {
            const maxPos = 800 - CELL_SIZE;
            let newFood;
            do {
                newFood = {
                    x: Math.floor(Math.random() * (maxPos/CELL_SIZE)) * CELL_SIZE,
                    y: Math.floor(Math.random() * (maxPos/CELL_SIZE)) * CELL_SIZE
                };
            } while(snake.some(seg => seg.x === newFood.x && seg.y === newFood.y)); // 防止食物出现在蛇身上
            return newFood;
        }

        // 移动与进食逻辑（网页1、网页5）
        function move() {
            // 如果游戏不在运行状态，则不执行移动逻辑
            if (!isGameRunning) return;
            
            const head = {...snake[0]};
            switch(direction) {
                case 'up': head.y -= CELL_SIZE; break;
                case 'down': head.y += CELL_SIZE; break;
                case 'left': head.x -= CELL_SIZE; break;
                case 'right': head.x += CELL_SIZE; break;
            }

            // 碰撞检测（网页8）
            if (head.x < 0 || head.x >= 800 || head.y < 0 || head.y >= 800 
                || snake.some(seg => seg.x === head.x && seg.y === head.y)) {
                // alert('游戏结束！得分：' + score);
                isGameRunning = false;
                clearInterval(gameInterval);
                showNotification('游戏结束！得分：' + score, 'warning');
                // 不再自动重置游戏，需要用户点击"游戏开始"按钮
                return;
            }

            snake.unshift(head);
            
            // 进食检测（网页2、网页9）
            if (head.x === food.x && head.y === food.y) {
                score += 10;
                document.getElementById('score').textContent = score;
                food = generateFood(); // 生成新食物
            } else {
                snake.pop();
            }

            updateDisplay();
        }

        // 画面更新（网页7）
        function updateDisplay() {
            const board = document.getElementById('game-board');
            board.innerHTML = '';
            
            // 绘制蛇身
            snake.forEach(pos => {
                const cell = document.createElement('div');
                cell.className = 'snake-cell';
                cell.style.left = pos.x + 'px';
                cell.style.top = pos.y + 'px';
                board.appendChild(cell);
            });

            // 绘制食物（网页10）
            const foodElement = document.createElement('div');
            foodElement.id = 'food';
            foodElement.style.left = food.x + 'px';
            foodElement.style.top = food.y + 'px';
            board.appendChild(foodElement);
        }

        // 方向控制（网页3、网页11）
        document.addEventListener('keydown', (e) => {
            const keyMap = {
                'ArrowUp': 'up',
                'ArrowDown': 'down',
                'ArrowLeft': 'left',
                'ArrowRight': 'right'
            };
            const newDir = keyMap[e.key];
            
            // 禁止180度转向
            if ((direction === 'up' && newDir === 'down') ||
                (direction === 'down' && newDir === 'up') ||
                (direction === 'left' && newDir === 'right') ||
                (direction === 'right' && newDir === 'left')) return;
                
            if (newDir) direction = newDir;
        });

        // 游戏重置
        function resetGame() {
            snake = [{x: 400, y: 400}];
            direction = 'right';
            score = 0;
            food = generateFood();
            document.getElementById('score').textContent = 0;
            isGameRunning = true;
            
            // 重新启动游戏循环
            if (gameInterval) {
                clearInterval(gameInterval);
            }
            gameInterval = setInterval(move, 220);
            updateDisplay();
        }

        // 通知功能
        function showNotification(message, type = 'success') {

            const notificationText = document.getElementById('notificationText');
            notificationText.textContent = message;
            
            notification.className = 'notification';
            
            // 获取 CSS 变量的值
            const rootStyles = getComputedStyle(document.documentElement);
            
            if (type === 'warning') {
                notification.style.background = rootStyles.getPropertyValue('--warning');
            } else if (type === 'error') {
                notification.style.background = rootStyles.getPropertyValue('--danger');
            } else {
                notification.style.background = rootStyles.getPropertyValue('--accent');
            }
            
            notification.classList.add('show');
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }

        // 初始显示
        updateDisplay();
        // 不再自动启动游戏循环，需要用户点击"游戏开始"按钮

        // 方向控制按钮
        document.getElementById('up-btn').addEventListener('click', () => {
            if (direction !== 'down') direction = 'up';
        });

        document.getElementById('down-btn').addEventListener('click', () => {
            if (direction !== 'up') direction = 'down';
        });

        document.getElementById('left-btn').addEventListener('click', () => {
            if (direction !== 'right') direction = 'left';
        });

        document.getElementById('right-btn').addEventListener('click', () => {
            if (direction !== 'left') direction = 'right';
        });

        // 游戏开始按钮事件处理
        document.getElementById('btn-start').addEventListener('click', () => {
            resetGame();
            showNotification('游戏开始！', 'success');
        });
    </script>
</body>
</html>